package com.ll.hangertv;

import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.ll.hangertv.common.Config;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

public class SplashActivity extends Activity {
    static  String TAG = "SplashActivity";
    private TextView textViewTimer;
    private static  int timeOut = 5;
    private static int msgCode = 100;
    private static boolean  timerStop = false;
    private  TimerHandler timerhandler ;
    public Context context;
    public Thread myThread ;
    public static String url = "";
    String[] permissions = new String[]
            {
                    /*Manifest.permission.CAMERA,*/
                    Manifest.permission.WRITE_EXTERNAL_STORAGE,
                    Manifest.permission.READ_EXTERNAL_STORAGE,
                   /* Manifest.permission.ACCESS_FINE_LOCATION,
                    Manifest.permission.ACCESS_COARSE_LOCATION,
                    Manifest.permission.BLUETOOTH,*/
                    Manifest.permission.ACCESS_NETWORK_STATE,
                    Manifest.permission.INTERNET,
            };
    // 声明一个集合，在后面的代码中用来存储用户拒绝授权的权
    List<String> mPermissionList = new ArrayList<>();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_splash);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);        context = this.getApplicationContext();


        try
        {
            timerStop = false;

            if (Build.VERSION.SDK_INT > 22)
            {
                mPermissionList.clear();
                for (int i = 0; i < permissions.length; i++)
                {
                    if (ContextCompat.checkSelfPermission(SplashActivity.this, permissions[i]) != PackageManager.PERMISSION_GRANTED)
                    {
                        mPermissionList.add(permissions[i]);
                    }
                }
                if (mPermissionList.isEmpty())
                {
                    //未授予的权限为空，表示都授予了
                    Toast.makeText(SplashActivity.this, "已经获取权限", Toast.LENGTH_LONG).show();
                } else
                {//请求权限方法
                    String[] permissions = mPermissionList.toArray(new String[mPermissionList.size()]);//将List转为数组
                    ActivityCompat.requestPermissions(SplashActivity.this, permissions, 2);
                }
            }

            timerhandler = new TimerHandler();
            timer.schedule(task, 100, 1000); //定时获取网络状态
            url = getUrl();
            Toast.makeText(context, url,Toast.LENGTH_SHORT).show();

            //url = "http://hcs.madest.com:9888/static/linepad/index.html#/login";
            if(url.length() == 0)
            {
                timer.cancel();
                timerStop = true;
                showInputDialog();
            }

            textViewTimer = (TextView) findViewById(R.id.timerId);

            textViewTimer.setOnClickListener(new View.OnClickListener()
            {
                @Override
                public void onClick(View view)
                {
                    timer.cancel();

                    showInputDialog();
                }
            });

            Config.init(timerhandler,context);

        }
        catch (Exception e)
        {
            e.printStackTrace();
            Toast.makeText(context, e.toString(), Toast.LENGTH_SHORT).show();

        }
    }


    void startMainActivityLoadUrl()
    {

        myThread =new Thread(){//创建子线程
            @Override
            public void run() {
                try
                {
                    sleep(timeOut*1000);//使程序休眠ji秒
                    Intent it=new Intent(getApplicationContext(),MainActivity.class);//启动MainActivity
                    startActivity(it);
                    finish();//关闭当前活动
                }catch (Exception e)
                {
                    e.printStackTrace();
                }
            }
        };
        myThread.start();//启动线程

    }


    void startMainActivity()
    {
        try
        {
            Intent it=new Intent(getApplicationContext(),MainActivity.class);//启动MainActivity
            startActivity(it);
            finish();//关闭当前活动
        }catch (Exception e)
        {
            e.printStackTrace();
        }

    }


    Timer timer = new Timer();
    private int timeOut0 = timeOut;
    TimerTask task = new TimerTask() {
        @Override
        public void run()
        {
            try
            {
            Message message = new Message();
            message.arg1 = msgCode;
            timerhandler.sendMessage(message);

            if(timerStop == true)

                return;

            timeOut0 --;
            if(timeOut0 <=0)
            {
                Message message0 = new Message();
                message0.arg1 = 101; //加载URL窗口
                timerhandler.sendMessage(message0);
            }
            }
            catch (Exception e)
            {
                e.printStackTrace();
            }
        }

        };

    class TimerHandler extends Handler
    {
        @Override
        //接收别的线程的信息并处理
        public void handleMessage(Message msg)
        {
            if(isFinishing())
            {
                return;
            }
            try
            {
                Log.i(TAG,msg.arg1+"");
                switch (msg.arg1)
                {
                    case 100:
                    {
                        textViewTimer.setText(getString(R.string.setting)+"("+timeOut0+" S)");
                    }break;
                    case 101:
                    {
                        startMainActivity();

                    }
                    break;
                    default:
                        break;

                }
            }
            catch (Exception e)
            {
                e.printStackTrace();
            }
        }
    }


    public static String urlFile = "/url.txt";

    private void showInputDialog()
    {
        /*@setView 装入一个EditView
         */
        timerStop = true;
        final EditText editText = new EditText(context);
        editText.setTextColor(this.getResources().getColor(R.color.colorAccent));
        if(url.length()==0)
           // editText.setText("http://192.168.100.99:8888/rest/core/show/tv");
            editText.setText("http://192.168.100.99:8888/static/linepad/index.html#/login");
        else
            editText.setText(url);

        AlertDialog.Builder inputDialog =
                new AlertDialog.Builder(SplashActivity.this);
        inputDialog.setTitle(getString(R.string.example)).setView(editText);
        inputDialog.setPositiveButton(getString(R.string.ok),
                new DialogInterface.OnClickListener()
                {
                    @Override
                    public void onClick(DialogInterface dialog, int which)
                    {
                        try
                        {
                            String url0 = editText.getText().toString().trim();
                            if(url0.indexOf("http://")<0)
                            {
                                Toast.makeText(context, getString(R.string.str2), Toast.LENGTH_SHORT).show();
                                return ;
                            }
                            url = url0;

                            File file =  new File(context.getFilesDir()+ urlFile);//存放于app默认安装目录文件管理器不可见
                            if (!file.exists())
                            {
                                Log.d(TAG, "create result:" + file.toString() + ":" + file.createNewFile());
                            }
                            FileInputStream in = new FileInputStream(file.toString());
                            OutputStream os = new FileOutputStream(file);
                            byte[] bytes = url.getBytes("UTF-8");
                            os.write(bytes, 0, bytes.length);
                            //关闭流
                            os.close();
                            os.flush();

                            Toast.makeText(context, getString(R.string.str3), Toast.LENGTH_SHORT).show();
                            startMainActivity();

                        }
                        catch (IOException i)
                        {
                            i.printStackTrace();
                        }
                    }
                }).show();

    }

    public String getUrl()
    {
        String urltmp = "";
        try
        {
            File file =  new File(context.getFilesDir()+ urlFile);//存放于app默认安装目录文件管理器不可见
            if (!file.exists())
            {
                Log.d(TAG, "create result:" + file.toString() + ":" + file.createNewFile());
            }
            Log.i(TAG,file.toString());
            FileInputStream in = new FileInputStream(file.toString());
            int len = 0;
            byte[] buf = new byte[1024];
            String strbuf;

            while ((len = in.read(buf)) != -1) {
                strbuf = new String(buf, 0, len);
                urltmp = urltmp + strbuf;
            }
            Log.i(TAG,urltmp);

           // Toast.makeText(context, urltmp,Toast.LENGTH_SHORT).show();
            in.close();
            //default
          //  url ="http://192.168.100.99:8888/static/linepad/index.html#/login";

        }
        catch (IOException i)
        {
            i.printStackTrace();
            Log.i(TAG,i.toString());
            Toast.makeText(context, i.toString(),Toast.LENGTH_SHORT).show();
        }
        finally
        {
            if(urltmp.length()==0)
            //return new String("http://"+"192.168.100.99:8888/rest/core/show/tv");
            return  new String("http://192.168.100.99:8888/static/linepad/index.html#/login");
            else
                return  urltmp ;
        }

    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        // TODO:  some code
       

    }


    @Override
    public void onStart() {
        super.onStart();

    }

    @Override
    public void onResume() {
        super.onResume();

    }

    @Override

    public void onStop() {
        super.onStop();

    }
}
